import { markAllInboxAsRead, pageInboxs } from 'apis/message';
import { useMessageStore } from 'store/message';
import { Icon } from '@iconify/react/dist/iconify.js';
import { Badge, Button, Card, Divider, Empty, Popover, Spin } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router';

const NoticeMessage = () => {
    const timeRef = useRef<NodeJS.Timeout | null>(null);
    const { waitReadCount, getUnreadMessage } = useMessageStore();
    const [list, setList] = useState<
        {
            title?: string;
            createTimeStr?: string;
        }[]
    >([]);
    const [loading, setLoading] = useState(false);
    const [markReadLoding, setMarkReadLoding] = useState(false);
    const navigate = useNavigate();
    const [open, setOpen] = useState(false);

    // methods
    const init = () => {
        getUnreadMessage();
    };
    const onOpenChange = (status: boolean) => {
        setOpen(status);
        if (status) {
            setLoading(true);
            pageInboxs({
                readTag: 1,
                pageNumber: 1,
                pageSize: 10,
            })
                .then((res) => {
                    setList(res?.recordDatas || []);
                })
                .finally(() => {
                    setLoading(false);
                });
        }
    };
    const handelToMessage = () => {
        navigate('/other/message');
        setOpen(false);
    };
    const handleReadALL = async () => {
        setMarkReadLoding(true);
        try {
            await markAllInboxAsRead({});
            setOpen(false);
            getUnreadMessage();
        } catch (error) {
        } finally {
            setMarkReadLoding(false);
        }
    };
    const handleToDetail = (item) => {
        navigate(`/other/message/${item?.id}`);
        setOpen(false);
    };

    useEffect(() => {
        init();
        timeRef.current = setInterval(() => {
            init();
        }, 1 * 60 * 1000);

        return () => {
            timeRef.current && clearInterval(timeRef.current);
        };
    }, []);

    const content = (
        <Spin spinning={loading}>
            <div className='w-400px'>
                {list?.length ? (
                    <div className='max-h-50vh overflow-y-auto pr-20px'>
                        {list.map((item, index) => (
                            <Badge.Ribbon text='未读' color='#ffb7b6' key={index}>
                                <Card
                                    className='hover:text-primary cursor-pointer mb-6px hover:border-primaryBg hover:bg-primaryBg'
                                    size='small'
                                    onClick={() => handleToDetail(item)}
                                >
                                    <span>{item?.title}</span>
                                    <div className='text-gray'>{item?.createTimeStr}</div>
                                </Card>
                            </Badge.Ribbon>
                        ))}
                    </div>
                ) : (
                    <Empty description='暂无站内信' className='mb-24px' />
                )}

                <Divider className='!my-12px' />
                <div className='flex justify-between items-center'>
                    {waitReadCount ? (
                        <Button
                            loading={markReadLoding}
                            type='link'
                            className='flex items-center justify-center'
                            onClick={handleReadALL}
                        >
                            <Icon icon='ant-design:check-outlined' width='16' height='16'></Icon>
                            全部已读
                        </Button>
                    ) : (
                        <div />
                    )}

                    <Button type='link' className='flex items-center justify-center' onClick={handelToMessage}>
                        查看全部站内信
                        <Icon icon='ant-design:right-outlined' width='16' height='16'></Icon>
                    </Button>
                </div>
            </div>
        </Spin>
    );
    return (
        <Popover
            open={open}
            onOpenChange={onOpenChange}
            content={content}
            title={
                <>
                    <div className='text-center text-16px mt-10px'>我的未读站内信</div>
                    <Divider className='!mt-12px !mb-0px' />
                </>
            }
            trigger='click'
        >
            <Badge
                count={waitReadCount}
                className={`px-12px block flex items-center h-38px rounded-38px transition-all ${
                    open ? 'bg-primaryBg text-primary' : 'bg-white'
                }`}
            >
                <Icon icon='icon-park-twotone:remind' width={18}></Icon>
            </Badge>
        </Popover>
    );
};

export default NoticeMessage;
